//
//  RdbLanguageSelectController.swift
//  rdb-led-banner
//
//  Created by radiobox3 on 2025/4/22.
//

import UIKit

class RdbLanguageSelectController: BaseViewController, UITableViewDataSource, UITableViewDelegate {

    var languages: Array<String> = []
    var isSelectedLanguage: Bool = false
    let RdbSystemLanguage = "systemlanguage"
    
    let supportLanguages = [
        "de",//德语
        "ar", //阿拉伯
        "el", //希腊
        "zh-Hans",//汉语
        "ja", //日本
        "en",//英语
        "uk", //乌克兰
        "it", //意大利
        "es-ES", //西班牙
        "ms",//马来西亚
        "sv",//瑞典
        "ko",//韩语
        "zh-Hant",//繁体中文
        "tr",//土耳其
        "pl", //波兰
        "pt-BR",//葡萄牙语
        "vi",//越南
        "es-MX",//墨西哥
        "ru",//俄语
        "fr",//法语
        "id",//印度尼西亚
        "nl", //荷兰语
        "th",//泰语
        "pt-PT",//葡萄牙
        "hi" //印度
    ]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.showBackButton = true
        self.view.backgroundColor = RdbColor.background.main.color
        self.view.addSubview(tableView)
        self.tableView.snp.makeConstraints{
            $0.edges.equalTo(UIEdgeInsets(top: UIDevice.navigationBarHeight(), left: 0, bottom: UIDevice.safeAreaBottom(), right: 0))
        }
        self.loadData()
    }
    
    @objc func loadData(){
        self.navigationItem.title = self.title
        self.isSelectedLanguage = RdbUserDefaults.boolValue(for: .rdbSystemLanguage)
        self.languages = Locale.availableLanguages().filter({ str in
            self.supportLanguages.contains(str)
        })
        self.languages.insert(RdbSystemLanguage, at: 0)
        self.tableView.reloadData()
        let section = self.isSelectedLanguage ? ( self.languages.firstIndex { language in
            return Locale.currentLanguage() == language
        } ?? 0 ) : 0
        self.tableView.selectRow(at: IndexPath(row: 0, section: section), animated: false, scrollPosition: .none)
    }
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: CGRect.zero, style: .insetGrouped)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = RdbColor.background.main.color
        tableView.separatorStyle = .none
        tableView.rowHeight = 50
        tableView.register(RdbLanguageTableViewCell.self, forCellReuseIdentifier: RdbLanguageTableViewCell.identified)
        tableView.showsVerticalScrollIndicator = false
        return tableView
    }()
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.languages.count
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return section == 0 ? 25.0 : 12.0
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.0001
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let language = self.languages[indexPath.section]
        guard let cell = tableView.dequeueReusableCell(withIdentifier: RdbLanguageTableViewCell.identified, for: indexPath) as? RdbLanguageTableViewCell else {
            return UITableViewCell()
        }
        if language == RdbSystemLanguage {
            cell.isSelected = !self.isSelectedLanguage
            cell.configData(RdbSystemLanguage.localized)
        } else {
            cell.isSelected = language == Locale.currentLanguage()
            cell.configData(language.localeDisplayName)
        }
       
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let language = self.languages[indexPath.section]
        if language == RdbSystemLanguage {
            Locale.resetCurrentLanguageToDefault()
            if self.isSelectedLanguage {
                RdbUserDefaults.remove(for: .rdbSystemLanguage)
            }
            self.isSelectedLanguage = false
        } else {
            Locale.setCurrentLanguage(language)
            if !self.isSelectedLanguage{
                RdbUserDefaults.update(value: true, keyPath: .rdbSystemLanguage)
            }
            self.isSelectedLanguage = true
        }
        RdbLanguageSelectController.reloadDisplayDirection()
        self.navigationController?.popViewController(animated: true)

    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: animated)
    }
    
    static func reloadDisplayDirection () {
        
        if Locale.isRTL() {
            UIView.appearance().semanticContentAttribute = .forceRightToLeft
            UISearchBar.appearance().semanticContentAttribute = .forceRightToLeft
            UIImageView.appearance().semanticContentAttribute = .forceRightToLeft
            UILabel.appearance().semanticContentAttribute = .forceRightToLeft
            UITextField.appearance().semanticContentAttribute = .forceRightToLeft
            UITextView.appearance().semanticContentAttribute = .forceRightToLeft
            UISlider.appearance().semanticContentAttribute = .forceRightToLeft
        } else {
            UIView.appearance().semanticContentAttribute = .forceLeftToRight
            UISearchBar.appearance().semanticContentAttribute = .forceLeftToRight
            UIImageView.appearance().semanticContentAttribute = .forceLeftToRight
            UILabel.appearance().semanticContentAttribute = .forceLeftToRight
            UITextField.appearance().semanticContentAttribute = .forceLeftToRight
            UITextView.appearance().semanticContentAttribute = .forceLeftToRight
            UISlider.appearance().semanticContentAttribute = .forceLeftToRight
        }
    }

    
}

class RdbLanguageTableViewCell: UITableViewCell{
    static let identified = "RdbLanguageTableViewCell"
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.selectionStyle = .default
        let view = UIView()
        view.backgroundColor = UIColor("#555555")
        self.selectedBackgroundView = view
        self.contentView.backgroundColor = UIColor("#555555")
        self.contentView.addSubview(self.iconImageView)
        self.contentView.addSubview(self.titleTextLabel)
        self.contentView.addSubview(self.circleImageView)
        self.iconImageView.snp.makeConstraints {
            $0.centerY.equalToSuperview()
            $0.leading.equalTo(15)
            $0.size.equalTo(CGSize(width: 20, height: 20))
        }
        
        self.titleTextLabel.snp.makeConstraints {
            $0.centerY.equalToSuperview()
            $0.leading.equalTo(45)
        }
        
        self.circleImageView.snp.makeConstraints {
            $0.centerY.equalToSuperview()
            $0.trailing.equalTo(-15)
            $0.size.equalTo(CGSize(width: 20, height: 20))
        }
    }
    
    func configData(_ title: String) {
        self.titleTextLabel.text = title
    }
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        self.circleImageView.isHighlighted = selected
        self.iconImageView.isHighlighted = selected
        if selected {
            self.titleTextLabel.textColor = RdbColor.shared.theme.color
        } else {
            self.titleTextLabel.textColor = UIColor.white
        }
    }
    
    lazy var iconImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "setting_global")
        imageView.highlightedImage = UIImage(named: "setting_global")?.withTintColor(RdbColor.shared.theme.color, renderingMode: .alwaysOriginal)
        return imageView
    }()
    
    lazy var titleTextLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.white
        label.font = UIFont.medium(14)
        return label
    }()
    
    lazy var circleImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        imageView.image = UIImage(named: "com_circle")
        imageView.highlightedImage = UIImage(named: "com_circle_sel")?.withTintColor(RdbColor.shared.theme.color, renderingMode: .alwaysOriginal)
        return imageView
    }()
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
